package cn.lijigou.shopping;


import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.domain.CityTag;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class HotPlaceActivity extends MActivity implements OnClickListener{
	private String city = "";
	
	private TextView back = null;
	private TextView register = null;
	private TextView title_center = null;
	private LinearLayout bottom_linear = null;
	private TextView tv = null;
	private View footerView;
	private TextView loding_text;
	private ExpandableListView listView  = null;
	private ExpandInfoAdapter adapter = null;
	private CityTag ct = null;
	private List<CityTag> tags = new ArrayList<CityTag>();
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler resultHander = new Handler(){
		
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
//			if(msg.what==0){
//				
//				tv = new TextView(HotPlaceActivity.this);  
//				tv.setText("抱歉，此城市无商圈");
//				tv.setTextColor(Color.BLACK);
//				tv.setGravity(Gravity.CENTER);   
//				bottom_linear.setVisibility(View.GONE);
//				LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);   
//				addContentView(tv, params);   
//				listView.setEmptyView(tv); 
//			}
//			if(msg.what==1){
//				register.setText(city);
//				adapter.notifyDataSetChanged();
//			}
//			if(msg.what==2){
//				tv.setVisibility(View.GONE);
//			}
			
			if(msg.what==0){
				tv = new TextView(HotPlaceActivity.this);  
				tv.setText("抱歉，此城市无商圈");
				tv.setTextColor(Color.BLACK);
				tv.setGravity(Gravity.CENTER);   
				bottom_linear.setVisibility(View.GONE);
				LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);   
				addContentView(tv, params);   
				listView.setEmptyView(tv); 
			}else if(msg.what==1){
				List<CityTag> temp = new ArrayList<CityTag>();
				for(CityTag cityTag:tags){
					temp.add(cityTag);
				}
				if(temp.size()>0){
					listView.removeFooterView(footerView);
				}else{
					Toast.makeText(HotPlaceActivity.this, "亲,没有这个城市的商圈信息..", 1).show();
				}
				adapter.setData(temp);
				adapter.notifyDataSetChanged();
			}else if(msg.what==2){
				tv.setVisibility(View.GONE);
			}else if(msg.what==3){
				listView.removeFooterView(footerView);
				View view=(View)footerView.findViewById(R.id.loding);
				view.setVisibility(View.GONE);
				Toast.makeText(HotPlaceActivity.this, "亲,没有这个城市的商圈信息..", 1).show();
			}else if(msg.what==4){
				View view=(View)footerView.findViewById(R.id.loding);
				view.setVisibility(View.VISIBLE);
				loding_text.setText("点击重新加载商圈.");
				loding_text.setOnClickListener(HotPlaceActivity.this);
			
				
			}else if(msg.what==5){
				View view=(View)footerView.findViewById(R.id.loding);
				view.setVisibility(View.VISIBLE);
				loding_text.setText("商圈加载中.");
			}
			
			
			
		}
			
			
			
			
	};
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);      
		this.setContentView(R.layout.hot_place);
		setViews();
		 
	}

	private void setViews() {
		back = (TextView)findViewById(R.id.title_btn_left);
		findViewById(R.id.titleLeftView).setOnClickListener(this);
		
		
		back.setBackgroundResource(R.drawable.title_back_normal);
		register = (TextView)findViewById(R.id.title_btn_right);
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		
		title_center = (TextView)findViewById(R.id.text_center);
		title_center.setText(R.string.shopping_district);
		bottom_linear = (LinearLayout)findViewById(R.id.bottom_linear);
		
		initListView();
		if(!"".equals(MSystem.selectCity)){
			register.setText(MSystem.selectCity);
			getArea();
		}else if(MSystem.mLocation!=null){
			register.setText(MSystem.mLocation.getCity());
			getArea();
		}else{
			register.setText("城市");
			Toast.makeText(this, "请选择城市", 1).show();
		}
		
	}
//	public void getArea(){
//		new Thread() {
//			public void run() {
//				showWait();
//				ct=new CityTag();
//				 MSystem.setHotPlace(ct);
//				 if(ct!=null){
//					 if(tv!=null){
//						 resultHander.sendEmptyMessage(2);
//					 }
//					 city = ct.getTag_name();
//					 tags = ct.getTags();
//					 resultHander.sendEmptyMessage(1);
//				 }else{
//					 resultHander.sendEmptyMessage(0);
//				 }
//				hideWait();
//			}
//		}.start();
//	}
	
	
	
	
	public void getArea() {
		executorService.execute(new Thread() {
			public void run() {
				// showWait();

				getAreaInfo();
				// hideWait();
			}
		});
	}
	
	
	
	TimerTask task = null;
	Timer timer = null;
	private void getAreaInfo(){
		if(task==null){
			task = new TimerTask() { 
				public void run() { 
					if(MSystem.mLocation!=null){
						resultHander.sendEmptyMessage(5);
						if(getNetConnectState(HotPlaceActivity.this)){
							timer.cancel();
							executorService.execute(new Thread() {
								public void run() {
									ct = new CityTag();
									MResult mResult = MSystem.setHotPlace(ct);
									if (mResult != null) {
										if (mResult.isSuccess()) {
											if (ct != null) {
												if (tv != null) {
													resultHander.sendEmptyMessage(2);
												}
												city = ct.getTag_name();
												tags = ct.getTags();
												resultHander.sendEmptyMessage(1);
											} else {
												resultHander.sendEmptyMessage(0);
											}
										} else {
											resultHander.sendEmptyMessage(3);
										}
									} else {
										resultHander.sendEmptyMessage(4);
									}
								}
							});
						}else{
							
						}
					 }
				} 
			}; 
		}
		if( timer==null){
			timer = new Timer(); 
			timer.schedule(task, 0,2000);
		}
	}
	
	
	
	public boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
	
 

	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleLeftView:
				this.finish();
			break;
			case R.id.titleRightView:
				search_item_city();
				break;
		}
	}
	public void initListView() {
		listView = (ExpandableListView) findViewById(R.id.expandable_list_view);
		adapter = new ExpandInfoAdapter(this);
		footerView= LayoutInflater.from(this).inflate(R.layout.local_text, null);
		View view=(View)footerView.findViewById(R.id.loding);
		view.setVisibility(View.VISIBLE);
		loding_text=(TextView)footerView.findViewById(R.id.loding_text);
		listView.addFooterView(footerView);
		
		listView.setAdapter(adapter);
		setListViewOnChildClickListener();
	}

	public void setListViewOnChildClickListener() {
		listView
				.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
					public boolean onChildClick(ExpandableListView parent,
							View v, int groupPosition, int childPosition,
							long id) {
						Intent intent_s = new Intent(HotPlaceActivity.this, HomeActivity.class);
						intent_s.putExtra("area", tags.get(groupPosition)
								.getTags().get(childPosition).getId()+"");
						intent_s.putExtra("areaName", tags.get(groupPosition)
								.getTags().get(childPosition).getTag_name());
						 
						MSystem.area = tags.get(groupPosition)
						.getTags().get(childPosition).getId()+"";
						if(childPosition==0){
							MSystem.areaName = tags.get(groupPosition)
							.getTag_name();
						}else{
							MSystem.areaName = tags.get(groupPosition)
							.getTags().get(childPosition).getTag_name();
						}
						
						
						HotPlaceActivity.this.setResult(2, intent_s);
						HotPlaceActivity.this.finish();
						return true;
					}
				});
		
		
		listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
			
			
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				 if(groupPosition==0){
					 MSystem.area ="";
					 MSystem.areaName ="";
					 HotPlaceActivity.this.finish();
				 }
				
					
				
				return false;
			}
		});  
		
		
		
		
		
		
		
		
	}

	public class ExpandInfoAdapter extends BaseExpandableListAdapter {
		LayoutInflater mInflater;
		Activity activity;
		List<CityTag> data =new ArrayList<CityTag>();
		public ExpandInfoAdapter(Activity a) {
			activity = a;
			mInflater = LayoutInflater.from(activity);
		}

		
		public void setData(List<CityTag> temp) {
			// TODO Auto-generated method stub
			this.data=temp;
		}
		
		public Object getChild(int groupPosition, int childPosition) {
			return data.get(groupPosition)
			.getTags().get(childPosition).getTag_name();
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		public int getChildrenCount(int groupPosition) {
		 
				return data.get(groupPosition)
				.getTags().size();
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			
			return getView(groupPosition, childPosition, convertView, parent);
		}

		public View getView(int groupPosition, int childPosition,
				View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item_icon_text,
						null);

				holder = new ViewHolder();
				holder.text = (TextView) convertView.findViewById(R.id.text);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			String name = data.get(groupPosition)
			.getTags().get(childPosition).getTag_name();
			holder.text.setText(name);

			return convertView;
		}

		public Object getGroup(int groupPosition) {
			return data.get(groupPosition).getTag_name();
		}

		public int getGroupCount() {
			
			return data.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			
			return getGroupViewStub(getGroup(groupPosition).toString(),isExpanded);
		}
		

		public RelativeLayout getGroupViewStub(String s,boolean isExpanded) {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, 64);
			RelativeLayout rl = new RelativeLayout(activity);
			rl.setLayoutParams(lp);

			RelativeLayout.LayoutParams lp_text = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT, 64);
			lp_text.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			lp_text.addRule(RelativeLayout.CENTER_VERTICAL);
			TextView text = new TextView(activity);
			text.setId(1);
			text.setLayoutParams(lp_text);
			text.setTextSize(20);
			text.setTextColor(Color.BLACK);
			text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			text.setPadding(30, 10, 10, 0);
			text.setText(s);
			rl.addView(text);
			rl.setBackgroundColor(Color.WHITE);
			
			
			RelativeLayout.LayoutParams lp_image = new RelativeLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT, 64);
			lp_image.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			ImageView image = new ImageView(activity);
			image.setPadding(0, 0, 30, 0);
			image.setLayoutParams(lp_image);
			if(isExpanded){
				image.setImageResource(R.drawable.hot_place_stand);
			}else{
				image.setImageResource(R.drawable.hot_place_down);
			}
			rl.addView(image);
			return rl;
		}

		public void onGroupExpanded(int groupPosition) {

		}

		public void onGroupCollapsed(int groupPosition) {
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		public boolean hasStableIds() {
			return false;
		}

	}

	static class ViewHolder {
		TextView text;
	}
	public void search_item_city(){
		Dialog dialog = null;
		Builder b2 = new AlertDialog.Builder(this);
		b2.setTitle(R.string.selected_city);
        b2.setItems(R.array.hot_place_city, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	String[] citys= getResources().getStringArray(R.array.hot_place_city);
            	city = citys[which].replace("　","");
            	register.setText(city);
            	tags.clear();
            	MSystem.selectCity = city;
            	getArea();
            }
        });
        dialog = b2.create();
        dialog.show();
	}
	public void showWait() {
		this.runOnUiThread(new Runnable() {
			public void run() {
				bottom_linear.setVisibility(View.VISIBLE);
			}
		});
	}
	public void hideWait() {
		this.runOnUiThread(new Thread() {
			public void run() {
				bottom_linear.setVisibility(View.GONE);
			}
		});
	}
	  
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    		HotPlaceActivity.this.finish();
	    	}
			return false;
	    	}
	
}
